/* entity */
import Field from '@model/entity/Field';
/* model */
import Column from '@model/types/Column';
/* service */
import { getFieldName, mergeFieldsWithProperty } from '@service/FieldService';
/* util */
import { simplifyTableColumnsProperty, saveDataToStorage, getDataToStorage } from '@src/modules/projectManage/projectManageList/util';
import { fieldArrayToObject } from '@src/util/array';
import { isEmpty } from '@src/util/type';
import _ from 'lodash';
import { Message } from 'element-ui';
import i18n from '@src/locales';
/* vue */
import { ref, nextTick } from 'vue';

export function useSelectColumn() {
  // 列
  const columns = ref([] as Column[]);

  // 构建选择列
  const buildSelectColumns = async (origin: Column[], storageKey: string) => {
    const localColumns = await getDataToStorage(storageKey, []);

    // 有本地缓存--列表排序
    const columnStatus = localColumns
      .map((i: any) => (typeof i == 'string' ? { field: i, show: true } : i))
      .reduce((acc: any, col: any, currentIndex: Number) => {
        acc[col.field] = {
          field: col,
          index: currentIndex,
        };
        return acc;
      }, {});

    const originFields = buildSortFields(origin, columnStatus);

    // 合并本地缓存列数据至当前实例的列数据
    mergeFieldsWithProperty(
      originFields,
      localColumns,
      (column: Column, localStorageDataColumnItem: Column) => {
        // 列名不匹配则返回
        if (getFieldName(column) !== getFieldName(localStorageDataColumnItem)) return;

        // 覆盖列显示状态
        // column.show = Boolean(localStorageDataColumnItem.show); // 因为有show = 'important'的存在，所以不能直接Boolean
        column.show = localStorageDataColumnItem.show;

        // 覆盖宽度数据
        if (localStorageDataColumnItem?.width) {
          column.width = localStorageDataColumnItem.width;
        }

        column.fixLeft = localStorageDataColumnItem.fixLeft && 'left';
      }
    )

    columns.value = [];
    nextTick(() => {
      columns.value = originFields;
    });
  }

  // 选择列排序
  const buildSortFields = (originFields: Column[] = [], fieldsMap: any = {}) => {
    let fields: Column[] = [];
    let unsortedFields: Column[] = [];

    originFields.forEach((originField: any) => {
      let { fieldName } = originField;
      let field = fieldsMap[fieldName];

      if (field) {
        let { index } = field;
        fields[index] = originField;
      } else {
        unsortedFields.push(originField);
      }
    });

    return fields.concat(unsortedFields);
  }
  
  // 保存选择列
  const saveSelectColumns = (value: { type: string, data: any[] }, storageKey: string) => {
    let newColumns = value.data || [];

    const NewColumnMap = newColumns.reduce((acc, col) => (acc[col.field] = col) && acc, {});

    // 列对象
    const OldColumnsMap: Record<string, Column> = fieldArrayToObject<Column>(columns.value);
    let oldColumn: Column;
    let newColumn: Column;
    let field: string;

    const originColumns = newColumns.map((column: Column) => {
      field = column.field || '';
      oldColumn = OldColumnsMap[field] || {};
      newColumn = NewColumnMap[field] || {};
      
      oldColumn.show = newColumn.show;
      oldColumn.width = newColumn.width;
      oldColumn.fixLeft = newColumn.fixLeft;
      
      return oldColumn;
    })

    // 精简选择列字段
    const showColumns = simplifyTableColumnsProperty(originColumns);

    // 保存到缓存
    saveDataToStorage(storageKey, showColumns);

    columns.value = [];
    nextTick(() => {
      columns.value = originColumns;
    });

    Message.success(i18n.t('common.base.saveSuccess') as string);
  }
  
  return {
    columns,
    buildSelectColumns,
    saveSelectColumns,
  }
}
